package javaweb_work01.main.Servlet;

import javaweb_work01.main.Utils.PageContrl;
import javaweb_work01.main.Entity.Students;
import javaweb_work01.main.Service.CountService;
import javaweb_work01.main.Service.DeleteService;
import javaweb_work01.main.Service.ShowService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 删除学员功能的Servlet
 */
@WebServlet(name = "DeleteServlet", urlPatterns = "/delete")
public class DeleteServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到点击删除的对应行的学员学号
        int delNum = Integer.parseInt(request.getParameter("delNum"));
        //作为参数传入对应Service,调用Dao层方法，删除指定学员信息
        DeleteService deleteService = new DeleteService();
        deleteService.deleteStudentsService(delNum);

        //获取主页需要显示的信息，构建主页
        //声明CountService类的对象，以便调用方法
        CountService countService = new CountService();
        //调用Service中的方法，最后调用Dao层方法，返回数据库中的数据总数，即学员总数
        int count = countService.countStudentsService();
        //利用得到的学员总数构造新的PageContrl对象，用于分页显示，此处为从第0条开始，显示10条
        PageContrl pageContrl = new PageContrl(0,10,count);
        //声明ShowService类的对象
        ShowService showService = new ShowService();
        //利用ShowService类的对象调用方法，最后调用Dao层方法，返回数据库中该页需要显示的学员信息
        List<Students> students = showService.showStudentsService(pageContrl);

        //将得到的PageContrl对象和Students对象放入session中实现共享
        request.getSession().setAttribute("pageContrl",pageContrl);
        request.getSession().setAttribute("showStudents",students);
        //跳转到主页
        response.sendRedirect("main.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
